<?php
/**
 * File description.
 * 
 * @filesource
 * @author Michael N <webjestic@gmail.com>
 * @link http://webjestic.net webJestic
 * @license http://www.opensource.org/licenses/bsd-license.php BSD
 * @copyright Copyright (c) 2009 - webJestic.NET.  All Rights Reserved.
 * 
 * @category   webJestic
 * @package    Library 
 * @subpackage Resources
 * @version    $Id$
 */

class Engine_Resource_Auth extends Zend_Application_Resource_ResourceAbstract {

	protected $_auth;
	protected $_adapter;
	protected $translate;	
	protected $log;
	
	public function init() {
		$this->translate = Zend_Registry::get('Zend_Translate');
		$this->log = Zend_Registry::get('Zend_Log');
		return $this->getAuth();
	}
	
	
	public function getAuth() {
		$options = $this->getOptions();
		$authNamespace = $options['namespace'];
		Zend_Registry::set('AuthNamespace', $authNamespace);
		
		// Create and configure Zend_Auth
		$this->_auth = Zend_Auth::getInstance();
		$this->_auth->setStorage(new Zend_Auth_Storage_Session($authNamespace));

		// Create and configure the Zend_Auth_Adapter
		$this->_adapter = new Zend_Auth_Adapter_DbTable(Zend_Registry::get('Zend_Db'));
		$this->_adapter->setTableName(CORE_USERS)
						->setIdentityColumn('user_email')
						->setCredentialColumn('user_password');
			 
		// TODO Convert into a Zend_Auth object...
		Zend_Registry::set('WJAuth', $this);
		return $this->_auth;
	}
	
	
	public function authenticate($values = null) {
		
		// Set the identity and credentials for the adapter
		$this->_adapter->setCredential($this->passwordTreatment($values['password']))
			 		   ->setIdentity($values['useremail']);	
			 		   
		// Modify the SELECT statement to include a WHERE clause
		// Auth WHERE clause
	//	$sql = $this->_adapter->getDbSelect();
	//	$sql->where('user_active = TRUE AND user_suspended = FALSE');
		
		// Authenticate the credentials and store basic user information to the session
		$result = $this->_auth->authenticate($this->_adapter);		
		if ($result->isValid()) {		 
			//	$this->_auth->getStorage()->write($this->_adapter->getResultRowObject());		
			$storage = $this->_auth->getStorage();
			$storage->write($this->_adapter->getResultRowObject(array(
					'user_id',
					'user_email',
					'user_firstname',
					'user_lastname',
					'user_username',
					'user_verification_code',
					'user_login_count',
					'user_login_date',
					'user_suspended',
					'user_active'
			)));			

			// UPDATE table CORE_USERS with login data
			$authRecord = $this->authRecord();
			$core_user = new Engine_Db_Table_CoreUsers();
			$data = array(	'user_login_date' => engine_date(),
							'user_login_count' => ($authRecord->user_login_count + 1)
			);
			$where = $core_user->getAdapter()->quoteInto('user_id = ?', $authRecord->user_id);
			$core_user->update($data, $where);
			
			// add log entry for login success
			$format = $this->translate->_('LOG_LOGIN');
			$entry = sprintf($format, $authRecord->user_id, $authRecord->user_username, $authRecord->user_email, $_SERVER['REMOTE_ADDR']);
			$this->log->info($entry);
		} else {
			// add log entry for login failure
			$format = $this->translate->_('LOG_LOGIN_FAILURE');
			$entry = sprintf($format, $values['useremail']);
			$this->log->info($entry);
		}
		
		// Return the results for further processing
		return $result;
	}
	
	
	public function authRecord() {
		// TODO Monitor depreciated function namespaceGet and update if necessary
		if ($this->isActive()) {
			$AuthObj = Zend_Session::namespaceGet(Zend_Registry::get('AuthNamespace'));
			return $AuthObj['storage'];
		} else {
			return null;
		}
		
	}
	
	public function passwordTreatment($password) {
		return md5($password.SITE_SALT);		
	}
	
	public function isActive() {
		if (Zend_Session::namespaceIsset(Zend_Registry::get('AuthNamespace'))) {
			return true;
		} else {
			return false;
		}
	}
	
	public function destroyAuthSession() {
		if (Zend_Session::namespaceIsset(Zend_Registry::get('AuthNamespace'))) {	
			Zend_Session::namespaceUnset(Zend_Registry::get('AuthNamespace'));
		}	
	}
	
	
}


?>